//
//  UIColor+Hex.swift
//  ZegoUIKit
//
//  Created by zego on 2022/7/20.
//

import Foundation
import UIKit

extension UIColor {
    public class func colorWithHexString(_ hexString: String, alpha: CGFloat = 1) -> UIColor {
        // 统一变大写
        var colorString = hexString.uppercased()
        // 删除空格
        colorString = colorString.replacingOccurrences(of: " ", with: "")
        // 替换头部
        colorString = colorString.replacingOccurrences(of: "#", with: "")
        colorString = colorString.replacingOccurrences(of: "0X", with: "")
        
        guard colorString.count == 6 else {
            print("[SpadgerColor] 请检查 hex 字符串长度是否正确")
            return UIColor.white
        }
        
        guard let intCode = Int(colorString, radix: 16) else {
            return UIColor.white
        }
        
        return UIColor.init(
            red: CGFloat((intCode >> 16) & 0xFF) / 255.0,
            green: CGFloat((intCode >> 8) & 0xFF) / 255.0,
            blue: CGFloat((intCode) & 0xFF) / 255.0,
            alpha: max(0, min(alpha, 1))
        )
    }
}

